package dao.impl;

import entity.StudentEntity;
import dao.StudentDao;
import dto.ChooseClassDTO;
import util.JDBCUtil;

import java.util.List;
import java.util.Map;

public class StudentDaoImpl extends JDBCUtil implements StudentDao {
    @Override
    public List<Map<String, Object>> getAll(String name) {
        String sql;
        List<Map<String, Object>> mapList;
        if ("null".equalsIgnoreCase(name)) {
            sql = "select * from student_info";
            mapList = queryForList(sql);
        } else if (name != null && !name.trim().isEmpty()) {
            sql = "select * from student_info where name like ?";
            String studentName = "%" + name + "%";
            mapList = queryForList(sql, studentName);
        } else {
            sql = "select * from student_info";
            mapList = queryForList(sql);
        }
        return mapList;
    }

    @Override
    public int addStudent(StudentEntity student) {
        String sql = "insert into student_info(id, student_id, academy_id, specialty_id, class_id, name, gender, age, grade, degree) values (?,?,?,?,?,?,?,?,?,?)";
        return insert(sql, student.getId(), student.getStudentId(), student.getAcademyId(), student.getSpecialtyId(), student.getClassId(), student.getName(), student.getGender(), student.getAge(), student.getGrade(), student.getDegree());
    }

    @Override
    public int deleteStudent(String id) {
        String sql = "delete student_info from student_info where id = ?";
        return delete(sql, id);
    }

    @Override
    public int updateStudent(StudentEntity student) {
        String sql = "update student_info set student_id = ?, academy_id = ?, specialty_id = ?, class_id = ?,name = ?,gender = ?,age = ?,grade = ?,degree = ? where id = ?";
        return update(sql, student.getStudentId(), student.getAcademyId(), student.getSpecialtyId(), student.getClassId(), student.getName(), student.getGender(), student.getAge(), student.getGrade(), student.getDegree(), student.getId());
    }

    @Override
    public int batchDeleteStudent(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        StringBuilder placeholders = new StringBuilder();
        for (int i = 0; i < ids.size(); i++) {
            placeholders.append("?");
            if (i < ids.size() - 1) {
                placeholders.append(",");
            }
        }

        String sql = "delete from student_info where id in (" + placeholders + ")";
        return delete(sql, ids.toArray());
    }

    @Override
    public int chooseClass(ChooseClassDTO dto) {
        String sql = "update student_info set class_id = ? where id = ?";
        return update(sql,dto.getClassId(),dto.getStudentId());
    }
}
